# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  #protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  def sha1(s)
    Digest::SHA1.hexdigest(s)
  end

  def read_binary(path)
    File.open path, "rb" do |f| f.read end
  end

  def array_rank(arr)
    rank_array = arr
    ranks = (0..arr.length-1).to_a.sort_by{ |x| arr[x] }
    rank = 1
    rank_array = Array.new
    ranks.each do |r|
      rank_array[r] = rank
      rank += 1
    end
    ranks.each_with_index do |r,i|
      val = arr[r]
      for loop in i+1..arr.length-1 do
        if arr[ranks[loop]]==val
          rank_array[ranks[loop]] = rank_array[ranks[i]]
        end
      end
    end
    return rank_array
  end

  def array_rank_desc(arr)
    rank_array = arr
    ranks = (0..arr.length-1).to_a.sort_by{ |x| arr[x] }
    ranks = ranks.reverse
    rank_array = Array.new
    ranks.each_with_index do |r,i|
      rank_array[r] = i+1
    end
    ranks.each_with_index do |r,i|
      val = arr[r]
      for loop in i+1..arr.length-1 do
        if arr[ranks[loop]]==val
          rank_array[ranks[loop]] = rank_array[ranks[i]]
        end
      end
    end
    return rank_array
  end

  def get_random_code
    Digest::SHA1.hexdigest("#{Time.now}#{random_string(8)}")
  end

  def random_string(len)
    #generate a random password consisting of strings and digits
    #chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    #chars = ("A".."Z").to_a + ("0".."9").to_a
    chars = ("a".."z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    newpass = newpass.gsub('I','1')
    newpass = newpass.gsub('l','1')
    newpass = newpass.gsub('o','1')
    newpass = newpass.gsub('O','1')
    newpass = newpass.gsub('0','1')
    return newpass
  end

  def admin_required
    if !session[:user]
      redirect_to :controller=>"welcome", :action=>"login"
    else
      if session[:user].admin_flag=='N'
        redirect_to :controller=>"welcome", :action=>"login"
      end
    end
  end
end
